package com.nowcoder.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.entity.User;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.MailUtil;
import com.nowcoder.utils.NowCoderUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import static com.nowcoder.utils.NowCoderConstant.*;

/**
 * @Author liujilong
 * @Project nowcoder
 * @File LoginController
 * @Date 2021/12/17 3:05 下午
 **/
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private MailUtil mailUtil;

    @GetMapping("/register")
    public String getRegisterPage() {
        return "/site/register";
    }

    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> register = userService.register(user);
        if (register == null || register.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了激活邮件，请尽快激活");
            model.addAttribute("target", "/index");

            return "/site/operate-result";
        } else {
            model.addAttribute("usernameMsg", register.get("usernameMsg"));
            model.addAttribute("passwordMsg", register.get("passwordMsg"));
            model.addAttribute("emailMsg", register.get("emailMsg"));

            return "/site/register";
        }
    }

    @GetMapping("/activation/{uid}/{code}")
    public String activation(Model model, @PathVariable("uid") String uid, @PathVariable("code") String code) {
        int result = userService.activation(uid, code);
        switch (result) {
            case ACTIVATION_SUCCESS:
            {
                model.addAttribute("msg", "激活成功，您的账号已经可以正常使用");
                model.addAttribute("target","/index");
                System.out.println("激活成功");
                break;
            }
            case ACTIVATION_REPEAT:
            {
                model.addAttribute("msg", "无效操作，激活码已过期");
                model.addAttribute("target","/index");
                System.out.println("激活码过期");
                break;
            }
            case ACTIVATION_FAILED:
            {
                model.addAttribute("msg", "激活失败，您使用的激活码不正确");
                model.addAttribute("target","/index");
                System.out.println("激活码错误");
                break;
            }
            default:
                break;
        }

        return "site/operate-result";
    }

    @GetMapping("/login")
    public String getLoginPage() {
        return "site/login";
    }

    @PostMapping("/login")
    public String login(String username, String password, String code, boolean rememberMe,
                        Model model, HttpSession session, HttpServletResponse response) {
        String kaptcha = (String) session.getAttribute("kaptcha");
        //检查验证码
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code)
                || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确");
            return "site/login";
        }

        //检查账号、密码
        int expirtion = rememberMe ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expirtion);
        if (map.containsKey("token")) {
            Cookie cookie = new Cookie("token", map.get("token").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expirtion);
            response.addCookie(cookie);

            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "site/login";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("token") String token) {
        userService.logout(token);
        return "redirect:/login";
    }

    // 忘记密码页面
    @GetMapping("/forget")
    public String getForgetPage() {
        return "/site/forget";
    }

    @GetMapping("/forget/code")
    @ResponseBody
    public String getForgetCode(String email, HttpSession session) {
        if (StringUtils.isBlank(email)) {
            return NowCoderUtil.getJSONString(1, "邮箱不能为空");
        }

        Context context = new Context();
        context.setVariable("email", email);
        String code = NowCoderUtil.generateUUID().substring(0, 4);
        context.setVariable("verifyCode", code);
        String content = templateEngine.process("/mail/forget", context);
        mailUtil.sendMail(email, "找回密码", content);

        session.setAttribute("verifyCode", code);

        return NowCoderUtil.getJSONString(0);
    }

    @PostMapping("/forget/password")
    public String resetPassword(String email, String verifyCode, String password, Model model, HttpSession session) {
        String code = (String) session.getAttribute("verifyCode");
        if (StringUtils.isBlank(verifyCode) || StringUtils.isBlank(code) || !code.equalsIgnoreCase(verifyCode)) {
            model.addAttribute("codeMsg", "验证码错误!");
            return "/site/forget";
        }

        Map<String, Object> map = userService.resetPassword(email, password);
        if (map.containsKey("user")) {
            return "redirect:/login";
        } else {
            model.addAttribute("emailMsg", map.get("emailMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/forget";
        }
    }

    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        //将验证码存入Session
        session.setAttribute("kaptcha", text);

        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }


}
